package cn.sinokj.party.chineseFourParty.utils.update;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import cn.sinokj.party.chineseFourParty.R;
import cn.sinokj.party.chineseFourParty.activity.FiringActivity;
import cn.sinokj.party.chineseFourParty.app.App;
import cn.sinokj.party.chineseFourParty.utils.logs.Logger;
import de.greenrobot.event.EventBus;

@SuppressWarnings("ResourceType")
public class UpdateManager {

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private Logger logger = Logger.getLogger();

    private Context mContext;

    private String apkUrl;// 返回的安装包url

    private Dialog downloadDialog;

    private boolean canWrite = Environment.getExternalStorageDirectory()
            .canWrite();

    private static final String savePath = App
            .getContext().getExternalCacheDir().getAbsolutePath(); // 下载包安装路径

    private static final String saveFileName = savePath + File.separator
            + "eDangJian.apk";

    private ProgressBar mProgress; // 进度条与通知ui刷新的handler和msg常量

    private static final int DOWN_UPDATE = 1;

    public static final int DOWN_OVER = 2;

    private int progress;

    private Thread downLoadThread;

    private boolean interceptFlag = false;

    private OnDismissListener onDismissListener;

    private boolean updateOperator = false;
    private TextView mTvPercent;

    public boolean isUpdateOperator() {
        return updateOperator;
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_UPDATE:

                    mProgress.setProgress(progress);
                    mTvPercent.setText(progress + "%");
                    break;
                case DOWN_OVER:
                    EventBus.getDefault().post(msg);
                    break;
                default:
                    break;
            }
        }

        ;
    };

    public UpdateManager(Context context, String url) {
        this.mContext = context;
        this.apkUrl = url;
    }

	/*// 外部接口让主Activity调用
	public void checkUpdateInfo() {
		showNoticeDialog();
	}

	private void showNoticeDialog() {
		final Dialog dialog = new Dialog(mContext, R.style.UpdateDialog);
		dialog.setContentView(R.xml.update_dialog);// 设置它的ContentView
		TextView dialog_text = (TextView) dialog.findViewById(R.id.dialog_text);
		TextView dialog_qrbtn = (TextView) dialog
				.findViewById(R.id.dialog_qrbtn);
		TextView dialog_fhbtn = (TextView) dialog
				.findViewById(R.id.dialog_fhbtn);
		dialog_text.setText("检测到新版本，请更新");
		dialog_qrbtn.setOnClickListener(new TextView.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				showDownloadDialog();
				dialog.dismiss();

			}
		});
		dialog_fhbtn.setOnClickListener(new TextView.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.setOnDismissListener(onDismissListener);
		dialog.show();
	}*/

    public void showDownloadDialog() {
        updateOperator = true;
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.update_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.progress);
        mTvPercent = (TextView) v.findViewById(R.id.tv_percent);
        downloadDialog = new AlertDialog.Builder(mContext)
                .setView(v)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        interceptFlag = true;
                        ((FiringActivity) mContext).toMainActivity();
                    }
                })
                .create();
        /*downloadDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "取消", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                interceptFlag = true;
                mContext.toMainActivity();
            }
        });*/
        downloadDialog.setCanceledOnTouchOutside(false);
        downloadDialog.show();
        downloadApk();
    }

    private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            logger.d("canWrite", canWrite);
            logger.d("saveFileName", saveFileName);
            try {
                URL url = new URL(apkUrl);

                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();

                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdir();
                }
                String apkFile = saveFileName;
                File ApkFile = new File(apkFile);
                FileOutputStream fos = new FileOutputStream(ApkFile);

                int count = 0;
                byte buf[] = new byte[1024];

                do {
                    int numread = is.read(buf);
                    count += numread;
                    progress = (int) (((float) count / length) * 100);
                    mHandler.sendEmptyMessage(DOWN_UPDATE);// 更新进度
                    if (numread <= 0) {
                        downloadDialog.dismiss();
                        mHandler.sendEmptyMessage(DOWN_OVER);// 下载完成通知安装
                        break;
                    }
                    fos.write(buf, 0, numread);
                } while (!interceptFlag);// 点击取消就停止下载.

                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                logger.e(e);
            } catch (IOException e) {
                logger.e(e);
            }

        }
    };

    // 下载apk
    private void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

	/*// 安装apk
	private void installApk() {
		File apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		mContext.startActivity(i);

	}*/

    public void setOnDismissListener(OnDismissListener onDismissListener) {
        this.onDismissListener = onDismissListener;
    }

    /**
     * Checks if the app has permission to write to device storage
     *
     * If the app does not has permission then the user will be prompted to
     * grant permissions
     *
     * @param activity
     *//*
	public static void verifyStoragePermissions(Activity activity) {
		// Check if we have write permission
		int permission = ActivityCompat.checkSelfPermission(activity,
				Manifest.permission.WRITE_EXTERNAL_STORAGE);

		if (permission != PackageManager.PERMISSION_GRANTED) {
			// We don't have permission so prompt the user
			ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
					REQUEST_EXTERNAL_STORAGE);
		}
	}*/

    /**
     * 安装apk文件
     */
    public void installApk() {
        System.out.println(savePath);
        File apkFile = new File(saveFileName);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        /*try {
            String[] command = {"chmod", "777", apkFile.toString()};
            ProcessBuilder builder = new ProcessBuilder(command);
            builder.start();
        } catch (IOException ignored) {
        }*/

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//            Uri contentUri = FileProvider.getUriForFile(mContext,
//                    BuildConfig.APPLICATION_ID + ".fileProvider", apkFile);
            String packageName = mContext.getPackageName();
            Uri contentUri = FileProvider.getUriForFile(mContext, packageName+ ".FileProvider", apkFile);
            mContext.grantUriPermission(packageName, contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
            mContext.grantUriPermission(packageName, contentUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            try {
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } catch (Exception e) {
                System.out.println(e);
                Toast.makeText(mContext, "没有权限安装", Toast.LENGTH_SHORT).show();
            }
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        mContext.startActivity(intent);
    }
}
